from django.shortcuts import render
from django.http import HttpResponse
from myadmin.models import Category, Shop, Product
from django.db.models import Q
from django.core.paginator import Paginator
from datetime import datetime
import time, os


# 菜品信息管理的视图文件
# Create your views here.

def index(request, pIndex=1):  # 浏览信息
    umod = Product.objects
    # 将已删除的店铺的菜品分类删除
    shop = Shop.objects.filter(status=9)
    category = Category.objects.filter(status=9)
    ulist = umod.filter(status__lt=9)
    for i in shop:
        for j in ulist:
            if i.id == j.shop_id:
                j.shop_id = str(j.shop_id)
                j.status = 9
                j.save()
    for i in category:
        for j in ulist:
            if i.id == j.category_id:
                j.category_id = str(j.category_id)
                j.status = 9
                j.save()
    ulist = umod.filter(status__lt=9)
    ulist = ulist.order_by("id")  # 对id排序
    # 获取并判断搜索条件
    mywhere = []
    kw = request.GET.get("category_id", None)
    keyword = request.GET.get("keyword", None)
    if kw:
        ulist = ulist.filter(Q(category_id=kw) & Q(status__lt=9))
        mywhere.append('category_id=' + kw)
    # 遍历当前菜品分类信息并封存对应信息
    for vo in ulist:
        sob = Shop.objects.get(id=vo.shop_id)
        vo.shopname = sob.name
        category = Category.objects.get(id=vo.category_id)
        vo.categoryname = category.name
    # 执行分页处理
    pIndex = int(pIndex)
    page = Paginator(ulist, 4)  # 以每页5条数据分页
    maxpage = page.num_pages  # 获取最大页数
    # 判断当前页是否越界
    if pIndex > maxpage:
        pIndex = maxpage
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)  # 获取当前页
    plist = page.page_range  # 获取页码列表
    context = {"productlist": list2, "plist": plist, "pIndex": pIndex, "maxpage": maxpage, "mywhere": mywhere}
    return render(request, "myadmin/product/index.html", context)


def add(request):  # 添加信息表单
    # 获取当前所有店铺
    slist = Shop.objects.values("id", 'name', "status")
    slist = slist.filter(status__lt=9)
    context = {"shopname": slist}
    return render(request, "myadmin/product/add.html", context)


def insert(request):  # 执行信息添加
    try:
        # 图片的上传处理
        myfile = request.FILES.get("cover_pic", None)
        if not myfile:
            return HttpResponse("没有菜品图片上传文件信息")
        cover_pic = str(time.time()) + "." + myfile.name.split('.').pop()
        destination = open("./static/uploads/product/" + cover_pic, "wb+")
        for chunk in myfile.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()

        ob = Product()
        ob.shop_id = request.POST['shop_id']
        ob.category_id = request.POST['category_id']
        ob.name = request.POST['name']
        ob.cover_pic = cover_pic
        ob.price = request.POST['price']

        ob.status = 1
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': '添加成功'}
    except Exception as err:
        print(err)
        context = {'info': '添加失败'}
    return render(request, "myadmin/info.html", context)


def delete(request, uid=0):  # 执行删除信息
    try:
        ob = Product.objects.get(id=uid)
        os.remove("./static/uploads/product/" + ob.cover_pic)
        ob.shop_id = str(ob.shop_id)
        ob.status = 9
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': "删除成功！"}
    except Exception as err:
        print(err)
        context = {'info': "删除失败！"}
    return render(request, "myadmin/info.html", context)


def edit(request, uid=0):  # 加载信息编辑表单
    try:
        ob = Product.objects.get(id=uid)
        # 遍历当前菜品分类信息并封存对应信息
        nowshopname = Shop.objects.get(id=ob.shop_id)
        slist = Shop.objects.values("id", 'name', "status")
        slist = slist.filter(Q(status__lt=9) & (~Q(id=ob.shop_id)))

        context = {'product': ob, 'shopname': slist, 'nowshopname': nowshopname}
        return render(request, "myadmin/product/edit.html", context)
    except Exception as err:
        print(err)
        context = {'info': '没有找到修改的信息'}
        return render(request, "myadmin/info.html", context)


def update(request, uid=0):  # 执行信息编辑
    try:
        # 获取原图片
        oldpicname = request.POST['oldpicname']
        # 图片的上传处理
        myfile = request.FILES.get("cover_pic", None)
        if not myfile:
            print(111)
            cover_pic = oldpicname
        else:
            print(222)
            cover_pic = str(time.time()) + "." + myfile.name.split('.').pop()
            destination = open("./static/uploads/product/" + cover_pic, "wb+")
            for chunk in myfile.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()

        ob = Product.objects.get(id=uid)
        ob.shop_id = request.POST['shop_id']
        ob.category_id = request.POST['category_id']
        ob.name = request.POST['name']
        ob.price = request.POST['price']
        ob.cover_pic = cover_pic
        ob.status = request.POST['status']
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': '修改成功！'}

        # 判断并删除老图片
        if myfile:
            os.remove("./static/uploads/product/"+oldpicname)

    except Exception as err:
        print(err)
        context = {'info': '修改失败！'}
        # 判断并删除老图片
        if myfile:
            os.remove("./static/uploads/product/"+cover_pic)

    return render(request, "myadmin/info.html", context)
